#include <windows.h>
#include <stdio.h>
#include <richedit.h>

#define bomFile "bom.txt"

DWORD CALLBACK EditStreamCallback(DWORD_PTR dwCookie, LPBYTE lpBuff,
        LONG cb, PLONG pcb)
{
    HANDLE hFile = (HANDLE)dwCookie;
    return (!ReadFile(hFile, lpBuff, cb, (DWORD *)pcb, NULL));
}

BOOL CreateBomFile(LPCTSTR pszFile)
{
    BYTE bomBuff[] = {0xef, 0xbb, 0xbf, 0xe5, 0xae, 0x8b, 0xe4, 0xbd, 0x93};
    DWORD size;
    HANDLE hFile = CreateFile(pszFile, GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

    if (hFile != INVALID_HANDLE_VALUE)
        if(!WriteFile(hFile, bomBuff, 9, &size, NULL))
        {
            CloseHandle(hFile);
            return FALSE;
        }

    CloseHandle(hFile);
    return TRUE;
}

BOOL FillRichEditFromFile(HWND hwnd, LPCTSTR pszFile)
{
    BOOL fSuccess = FALSE;
    HANDLE hFile = CreateFile(pszFile, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
    if (hFile != INVALID_HANDLE_VALUE) {
        EDITSTREAM es = { (DWORD_PTR)hFile, 0, EditStreamCallback };
        if (SendMessage(hwnd, EM_STREAMIN, SF_TEXT, (LPARAM)&es) && es.dwError == 0) 
        {
            fSuccess = TRUE;
        }
        CloseHandle(hFile);
    }
    return fSuccess;
}

static HMODULE hmoduleRichEdit;

int main(void)
{
    HWND hwndRichEdit;
    int r;
    EDITSTREAM es;
    BYTE buffer[4096] = {0};
    char * p;

    hmoduleRichEdit = LoadLibrary("RICHED20.DLL");

    hwndRichEdit = CreateWindowA(RICHEDIT_CLASS, NULL, ES_MULTILINE|WS_POPUP|WS_HSCROLL|WS_VSCROLL |WS_VISIBLE, 0, 0, 200, 60, NULL, NULL, hmoduleRichEdit, NULL);

    CreateBomFile(bomFile);
    FillRichEditFromFile(hwndRichEdit, bomFile);

    SendMessage(hwndRichEdit, WM_GETTEXT, 1024, (LPARAM)buffer);
    printf("buffer is %s\n", buffer);
    printf("buffer is: 0x%x-0x%x-0x%x-0x%x, expect 0xcb-0xce-0xcc-0xe5\n", buffer[0], buffer[1], buffer[2], buffer[3]);

    DestroyWindow(hwndRichEdit);

    return 0;
}
